<template>
  <div class="main user-layout-register">
    <h3><span>注册</span></h3>
    <a-form :wrapper-col="wrapperCol">
      <a-form-item v-bind="validateInfos.email">
        <a-input
          size="large"
          type="text"
          placeholder="邮箱"
          v-model:value="modelRef.email"
        ></a-input>
      </a-form-item>

      <a-popover
        placement="rightTop"
        :trigger="['focus']"
        :getPopupContainer="(trigger) => trigger.parentElement"
        :visible="pswState.passwordLevelChecked"
      >
        <template #content>
          <div :style="{ width: '240px' }" >
            <div :class="['user-register', passwordLevelClass]">强度：<span>{{ passwordLevelName }}</span></div>
            <a-progress :percent="pswState.percent" :showInfo="false" :strokeColor="passwordLevelColor " />
            <div style="margin-top: 10px;">
              <span>请至少输入 6 个字符。请不要使用容易被猜到的密码。</span>
            </div>
          </div>
        </template>
        <a-form-item v-bind="validateInfos.password">
          <a-input-password
            size="large"
            @click="handlePasswordInputClick"
            placeholder="至少6位密码，区分大小写"
            v-model:value="modelRef.password"
          ></a-input-password>
        </a-form-item>
      </a-popover>

      <a-form-item v-bind="validateInfos.password2">
        <a-input-password
          size="large"
          placeholder="确认密码"
          v-model:value="modelRef.password2"
        ></a-input-password>
      </a-form-item>
      <a-form-item v-bind="validateInfos.mobile">
        <a-input-group size="large" compact>
          <a-select style="width: 20%" size="large" defaultValue="+86">
            <a-select-option value="+86">+86</a-select-option>
            <a-select-option value="+87">+87</a-select-option>
          </a-select>
          <a-input
            style="width: 80%"
            size="large"
            placeholder="11 位手机号"
            v-model:value="modelRef.mobile"
          ></a-input>
        </a-input-group>
      </a-form-item>
      <a-form-item v-bind="validateInfos.captcha">
        <a-row :gutter="16">
          <a-col class='gutter-row' :span="16">
            <a-input size='large' type='text' placeholder='验证码' v-model:value="modelRef.captcha">
              <template #prefix><MailOutlined style="{ color: 'rgba(0,0,0,.25)' }" /></template>
            </a-input>
          </a-col>
          <a-col class='gutter-row' :span="8">
            <sms-code :mobile="modelRef.mobile"></sms-code>
          </a-col>
        </a-row>
      </a-form-item>
      <a-form-item :wrapper-col="wrapperCol">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="register-button"
          :loading="registerBtn"
          @click.stop.prevent="handleSubmit"
          :disabled="registerBtn"
        >
          注册
        </a-button>
        <router-link class="login" :to="{ name: 'login' }">使用已有账户登录</router-link>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import { computed, defineComponent, getCurrentInstance, reactive, toRaw, toRefs } from 'vue'
import { useForm } from '@ant-design-vue/use'
import { levelClass, levelNames, levelColor } from './constant'
import { pattern } from '@/utils/validate'
import { MailOutlined } from '@ant-design/icons-vue'
import SmsCode from './components/SmsCode'
import useDevice from '@/hooks/useDevice'

export default defineComponent({
  components: {
    SmsCode,
    MailOutlined
  },
  setup() {
    const { ctx } = getCurrentInstance()

    const state = reactive({
      wrapperCol: { span: 24 },
      modelRef: {
        email: '',
        password: '',
        password2: '',
        mobile: '',
        captcha: ''
      },
      pswState: {
        passwordLevel: 0,
        passwordLevelChecked: false,
        percent: 10,
        progressColor: '#FF0000'
      },
      passwordLevelClass: computed(() => levelClass[state.pswState.passwordLevel]),
      passwordLevelName: computed(() => levelNames[state.pswState.passwordLevel]),
      passwordLevelColor: computed(() => levelColor[state.pswState.passwordLevel]),
      registerBtn: false
    })

    const { isMobile } = useDevice()

    const handlePasswordLevel = (rule, value, callback) => {
      let level = 0
      // 判断这个字符串中有没有数字
      if (/[0-9]/.test(value)) {
        level++
      }
      // 判断字符串中有没有字母
      if (/[a-zA-Z]/.test(value)) {
        level++
      }
      // 判断字符串中有没有特殊符号
      if (/[^0-9a-zA-Z_]/.test(value)) {
        level++
      }
      state.pswState.passwordLevel = level
      state.pswState.percent = level * 30
      if (level >= 2) {
        if (level >= 3) {
          state.pswState.percent = 100
        }
        return Promise.resolve()
      } else {
        if (level === 0) {
          state.pswState.percent = 10
        }
        const ErrorText = !value ? '至少6位密码，区分大小写' : '密码强度不够'
        return Promise.reject(ErrorText)
      }
    }

    const handlePasswordCheck = (rule, value, callback) => {
      const password = state.modelRef.password
      if (!value) {
        return Promise.reject('请输入确认密码')
      }
      if (value && password && value.trim() !== password.trim()) {
        return Promise.reject('两次密码不一致')
      }
      return Promise.resolve()
    }

    const handlePasswordInputClick = () => {
      if (!isMobile.value) {
        state.pswState.passwordLevelChecked = true
        return
      }
      state.pswState.passwordLevelChecked = false
    }

    const handleSubmit = (e) => {
      e.preventDefault()
      validate()
        .then(() => {
          console.log(toRaw(state.modelRef))
          const values = toRaw(state.modelRef)
          ctx.$router.push({ name: 'registerResult', params: { ...values } })
        })
        .catch(err => {
          console.log('error', err)
        })
    }

    const rulesRef = reactive({
      email: [
        {
          required: true,
          type: 'email',
          message: '请输入邮箱地址'
        }
      ],
      password: [
        {
          required: true,
          validator: handlePasswordLevel,
          trigger: ['change', 'blur']
        },
      ],
      password2: [
        {
          required: true,
          validator: handlePasswordCheck,
          trigger: ['change', 'blur']
        },
      ],
      mobile: [
        {
          required: true,
          message: '请输入正确的手机号',
          pattern: pattern.mobile,
          trigger: ['change', 'blur']
        }
      ],
      captcha: [
        {
          required: true,
          message: '请输入验证码',
          trigger: 'blur',
        },
      ],
    })

    const { validate, validateInfos } = useForm(state.modelRef, rulesRef)

    return {
      ...toRefs(state),
      validateInfos,
      handlePasswordInputClick,
      handleSubmit
    }
  }
})
</script>

<style lang="less">
.user-register {
  &.error {
    color: #ff0000;
  }
  &.warning {
    color: #ff7e05;
  }
  &.success {
    color: #52c41a;
  }
}
.user-layout-register {
  .ant-input-group-addon:first-child {
    background-color: #fff;
  }
}
</style>

<style lang="less" scoped>
.user-layout-register {
  & > h3 {
    font-size: 16px;
    margin-bottom: 20px;
  }
  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }
  .register-button {
    width: 50%;
  }
  .login {
    float: right;
    line-height: 40px;
  }
}
</style>